package com.mew.auc.service;

import com.mew.common.config.RedisConstantValue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Service
@Slf4j
public class WhiteListService {
    private Timer timer = new Timer();
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private HashSet<Long> userList = new HashSet<>();

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    public void run(){
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                updateList();
            }
        }, 0, 60000);
    }

    private void updateList() {

        List<Object> list = redisTemplate.opsForHash().values(RedisConstantValue.ADMIN_WHITE_LIST);

        lock.writeLock().lock();
        userList.clear();

        try {
            if (list != null && !list.isEmpty()) {
                for (Object o : list) {
                    int temp = (int)o;
                    userList.add((long)temp);
                }
            }
        }
        catch (Exception e){
            log.error(e.getMessage());
        }
        finally {
            lock.writeLock().unlock();
        }
    }

    public boolean isInWhiteList(Long id){
        boolean ret = false;

        lock.readLock().lock();

        ret = userList.contains(id);

        lock.readLock().unlock();;

        return ret;
    }

}
